//
//  STNavigationController.swift
//  RouterPushProtocol
//
//  Created by Toj on 2/22/22.
//

import UIKit

enum STNavigationStyle: Int {
    case white
    case black
    
    var titleColor: UIColor {
        switch self {
        case .white:
            return UIColor(hex: "#171B22")
        case .black:
            return .white
        }
    }
    
    var backgroundColor: UIColor {
        switch self {
        case .white:
            return .white
        case .black:
            return UIColor(hex: "#171B22")
        }
    }
    
    var backIcon: String {
        switch self {
        case .white:
            return "com_nav_back_black"
        case .black:
            return "com_nav_back_white"
        }
    }
}

class STNavigationController: UINavigationController {
    
    open override var shouldAutorotate: Bool {
        return topViewController?.shouldAutorotate ?? false
    }

    // 支持哪些屏幕方向
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return topViewController?.supportedInterfaceOrientations ?? .portrait
    }

    open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }
    
    var style: STNavigationStyle = .white
    
    // override public var preferredStatusBarStyle: UIStatusBarStyle {
    // print("-->toj: " + #function)
    // return style == .white ? .default : .lightContent
    // }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 判断是否是暗黑模式
        var isDark = false
        if #available(iOS 12.0, *) {
            isDark = traitCollection.userInterfaceStyle == .dark
        }
        // print("-->toj: \(isDark), func:" + #function)
        
        style = isDark ? .black : .white
        style = .black
        setupNavigationBar()
        interactivePopGestureRecognizer?.delegate = self
        delegate = self
        view.backgroundColor = .white
    }
//
//    override func viewDidAppear(_ animated: Bool) {
//        super.viewDidAppear(animated)
//
//        // 当页面完全显示viewDidAppear后在开启侧滑 (目前验证可以不设置, 为了完整性设置了)
//        interactivePopGestureRecognizer?.isEnabled = true
//    }
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        print("-->toj: push animated:\(animated)")
        // print("-->toj: \(viewController)" + #function)
        if viewControllers.count >= 1 {
            viewController.hidesBottomBarWhenPushed = true
            var target: UIViewController = self
            let action = #selector(didTapBack(sender:))
            if viewController.responds(to: action) {
                target = viewController
            }
            
            let item = UIBarButtonItem(target: target, action: action, for: .touchUpInside, imageNormal: style.backIcon)
            viewController.navigationItem.leftBarButtonItem = item
        }
        
        // 禁用侧滑 防止ViewController Push过程中侧滑后界面显示异常,
        // 当页面完全显示viewDidAppear后在开启侧滑 (目前验证可以不设置, 为了完整性设置了)
        //interactivePopGestureRecognizer?.isEnabled = false
        super.pushViewController(viewController, animated: animated)
    }
    
    /*
     * 如果点击返回后BottomBar隐藏可以打开下面设置
     */
//    override public func popToRootViewController(animated: Bool) -> [UIViewController]? {
//        if viewControllers.count > 1 {
//            topViewController?.hidesBottomBarWhenPushed = false
//        }
//
//        return super.popToRootViewController(animated: animated)
//    }
    
    @objc private func didTapBack(sender: Any) {
        // print("-->toj: " + #function)
        _ = popViewController(animated: true)
    }
    
    private func setupNavigationBar() {
        // print("-->toj: setupNavigationBar")
        let appearance = UINavigationBar.appearance()
        // 半透明的
        appearance.isTranslucent = true

        // barStyle = .black: 那么系统栏就是 .lightContent 也就是白色
        // barStyle = .default: 那么系统栏就也是默认的黑色了
        appearance.barStyle = .black
        appearance.shadowImage = UIImage()
        appearance.backIndicatorImage = UIImage()

        appearance.backIndicatorTransitionMaskImage = UIImage()
        
        // 背景色
        let backgroundColor = style.backgroundColor//.tt_alpha(0.8)
        let backgroundImage = backgroundColor.to_image
        appearance.barTintColor = backgroundColor
        
        if #available(iOS 15.0, *) {
            let _appearance = UINavigationBarAppearance()
            _appearance.configureWithTransparentBackground()
            _appearance.backgroundColor = backgroundColor
            _appearance.backgroundImage = backgroundImage
            // 去掉导航栏下面的分割线
            _appearance.shadowImage = UIImage()
            // 阴影颜色, clear是没有阴影
            _appearance.shadowColor = .clear
            // 去掉半透明效果
            _appearance.backgroundEffect = nil
            // 导航栏标题颜色
            _appearance.titleTextAttributes = [.foregroundColor: style.titleColor]
            // 常规标准
            appearance.standardAppearance = _appearance
            // scrollView 下拉状态/ 滚动状态时的外观
            appearance.scrollEdgeAppearance = _appearance
        }
        else{
            // 导航栏标题颜色
            appearance.titleTextAttributes = [.foregroundColor: style.titleColor]
            appearance.setBackgroundImage(backgroundImage, for: .default)
            appearance.backgroundColor = backgroundColor
        }
        
        // 阴影颜色
        // navigationBar.layer.shadowColor = UIColor.black.cgColor
        // navigationBar.layer.shadowOffset = CGSize(width: 0, height: 0.5)
        // navigationBar.layer.shadowRadius = 3
        // navigationBar.layer.shadowOpacity = 0.24
        // navigationBar.clipsToBounds = false
    }
}

extension STNavigationController: UIGestureRecognizerDelegate {
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return viewControllers.count > 1
    }
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        let isGesture =
        gestureRecognizer.isKind(of: UIPanGestureRecognizer.classForCoder()) &&
        otherGestureRecognizer.isKind(of: UIScreenEdgePanGestureRecognizer.classForCoder())
        return isGesture
    }
}

extension STNavigationController: UINavigationControllerDelegate {
//    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
//        if (1 == navigationController.viewControllers.count) {
//               self.viewController = nil;
//           } else {
//               self.viewController = viewController;
//           }
//    }
}
